import React, { useEffect, useRef } from "react";

interface SimplePAGPlayerProps {
  /**
   * PAG文件路径或URL
   */
  src: string;
  /**
   * 是否自动播放
   * @default true
   */
  autoPlay?: boolean;
  /**
   * 是否循环播放
   * @default false
   */
  loop?: boolean;
  /**
   * 组件宽度
   * @default '100%'
   */
  width?: number | string;
  /**
   * 组件高度
   * @default '100%'
   */
  height?: number | string;
  /**
   * 加载完成回调
   */
  onLoad?: () => void;
  /**
   * 错误回调
   */
  onError?: (error: Error) => void;
}

const SimplePAGPlayer: React.FC<SimplePAGPlayerProps> = ({
  src,
  autoPlay = true,
  loop = false,
  width = "100%",
  height = "100%",
  onLoad,
  onError,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (!canvasRef.current) return;

    let pagView: any = null;

    const initPAG = async () => {
      try {
        // 动态导入libpag
        if (!window.libpag) {
          await new Promise((resolve) => {
            const check = () => {
              if (window.libpag) resolve(true);
              else setTimeout(check, 100);
            };
            check();
          });
        }

        const PAG = await window.libpag.PAGInit();

        // 加载PAG文件
        const response = await fetch(src);
        const buffer = await response.arrayBuffer();
        const pagFile = await PAG.PAGFile.load(buffer);

        // 初始化PAG视图
        pagView = await PAG.PAGView.init(pagFile, canvasRef.current!);

        // 设置播放参数
        pagView.setRepeatCount(loop ? 0 : 1); // 0表示无限循环

        // 自动播放
        if (autoPlay) {
          pagView.play();
        }

        onLoad?.();
      } catch (error) {
        console.error("PAG初始化失败:", error);
        onError?.(error as Error);
      }
    };

    initPAG();

    // 清理函数
    return () => {
      if (pagView) {
        pagView.destroy();
      }
    };
  }, [src, autoPlay, loop]);

  return (
    <canvas
      ref={canvasRef}
      style={{
        width,
        height,
        display: "block",
      }}
    />
  );
};

export default SimplePAGPlayer;
